import axios from 'axios'
import { getToken } from '@/utils/auth'
import { formatStr } from '@/utils/chenxi'
const apiVersion = "v1";
// 新增素材资源
const createTokenUrlOfLocal = "{1}/local-oss/{2}/{3}/create-token"
const uploadUrlOfLocal = "{1}/local-oss/{2}/{3}/upload-file"
export function uploadFile(storage, file, processCallback) {
    switch (storage.storageType) {
        case "local_filesystem":
            return uploadLocalFile(storage, file);
            break;
        default:
            return Promise.reject("暂不支持该存储类型");
    }
}

async function uploadLocalFile(storage, file, processCallback){
    let baseUrl = storage.storageConfig.uploadUrl;
    if (baseUrl && baseUrl.length > 0 && baseUrl.endsWith("/")) {
        baseUrl = baseUrl.substring(0, baseUrl.length - 1);
    }
    let res = await getUploadToken(baseUrl, storage.id, storage.storageType);
    let uploadToken = res.data.data;
    let uploadUrl = formatStr(uploadUrlOfLocal, baseUrl, apiVersion, storage.storageType);
    let formData = new FormData();
    formData.append("file", file.file);
    return axios({
        method: 'post',
        url: uploadUrl,
        data: formData,
        params: {uploadToken: uploadToken.token, },
        onUploadProgress: event =>{
            let num = event.loaded / event.total * 100 | 0;
            file.onProgress({percent: num})
        },
        headers: {
            'Content-Type' : 'multipart/form-data',
            'Authorization': 'Bearer ' + getToken()
        }
    })
}

function getUploadToken(baseUrl, storageId, storageType){
    let createTokenUrl = formatStr(createTokenUrlOfLocal, baseUrl, apiVersion, storageType);
    return axios({
        method: 'get',
        url: createTokenUrl,
        params: {storageId: storageId},
        headers: { 'Authorization': 'Bearer ' + getToken() }
        });
}
